package com.sgcc.isc.controller;

import com.sgcc.common.log.annotation.Log;
import com.sgcc.common.log.enums.BusinessType;
import com.sgcc.common.security.annotation.PreAuthorize;
import com.sgcc.isc.core.orm.complex.FunctionNode;
import com.sgcc.isc.core.orm.complex.FunctionTree;
import com.sgcc.isc.core.orm.domain.BusinessApplication;
import com.sgcc.isc.core.orm.identity.User;
import com.sgcc.isc.core.orm.organization.BusinessOrganization;
import com.sgcc.isc.domain.SysDistrict;
import com.sgcc.isc.service.ISysDistrictService;
import com.sgcc.isc.service.adapter.factory.AdapterFactory;
import com.sgcc.system.api.RemoteUserService;
import com.sgcc.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 登录验证
 * 
 * @author sgcc
 */
@RestController
@RequestMapping("/syn")
public class SynController
{
	@Autowired
    private ISysDistrictService sysDistrictService;
	@Autowired
	private RemoteUserService remoteUserService;
	@Value("${isc.ordId}")
	private String ordId;
	//@Value("${isc.systemId}")
	//private String systemId;
	@Value("${isc.systemName}")
	private String systemName;
	@Value("${isc.pwd}")
	private String pwd;
	
	private void getDeptAll(List<BusinessOrganization> list,String id) throws Exception {

		try {
			List<BusinessOrganization> dept=AdapterFactory.getOrganizationService().getChildBusiOrgsById(id,null);
			if(dept!=null && dept.size()>0) {
				list.addAll(dept);
				for (BusinessOrganization department : dept) {
					getDeptAll(list,department.getId());
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	//@PreAuthorize(hasPermi = "isc:dept:update")
    @Log(title = "ISC同步业务组织", businessType = BusinessType.UPDATE)
    @RequestMapping("/dept")
    public boolean syncDept()
    {
    	try {
    		List<BusinessOrganization> dept=new ArrayList<BusinessOrganization>();
			getDeptAll(dept,ordId);
    		Map<String,String> orgP=new HashMap<String,String>();
    		for (BusinessOrganization department : dept) {
    			orgP.put(department.getId(), department.getParentId());
			}
    		for (BusinessOrganization department : dept) {
    			SysDistrict sysDistrict=sysDistrictService.selectSysDistrictById(department.getId());
    			if(null==sysDistrict) {
    				String p="";
    				p=getP(department.getId(),orgP,p)+department.getId();
    				sysDistrict=new SysDistrict();
    				sysDistrict.setDistrictId(department.getId());
    				sysDistrict.setParentId(department.getParentId());
    				sysDistrict.setDistrictName(department.getName());
    				sysDistrict.setParentId(department.getParentId());
					sysDistrict.setOrgId(department.getUnicode());
					sysDistrict.setCreateTime(new Date());
    				sysDistrict.setAncestors(p);
    				sysDistrictService.insertSysDistrictIsc(sysDistrict);
    			}else {
    				String p="";
    				p=getP(department.getId(),orgP,p)+department.getId();
    				sysDistrict=new SysDistrict();
    				sysDistrict.setDistrictId(department.getId());
    				sysDistrict.setParentId(department.getParentId());
    				sysDistrict.setDistrictName(department.getName());
    				sysDistrict.setParentId(department.getParentId());
					sysDistrict.setOrgId(department.getUnicode());
					sysDistrict.setUpdateTime(new Date());
    				sysDistrict.setAncestors(p);
    				sysDistrictService.updateSysDistrict(sysDistrict);
    			}
			}
    		return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
    }
	private static String getP(String id,Map<String,String> orgP,String path) {
		if(null==orgP.get(id)) {
			return path;
		}
		path=orgP.get(id)+","+path;
		return getP(orgP.get(id),orgP,path);
	}

	/**
	 * 获取用户有权限访问的子功能集合(得到所有权限范围内的菜单名字进行对比)
	 */
	@RequestMapping("/getFuncsByParentId/{iscUserid}")
	public List<String> getFuncsByParentId(@PathVariable("iscUserid") String iscUserid){
		List<String> menus = new ArrayList<>();
		try {
			//ISC中当前系统ID
			String systemId = "";
			//获取ISC中所有的系统
			List<BusinessApplication> businessApplications = AdapterFactory.getDomainService().getBusinessApplication();
			if(businessApplications != null && businessApplications.size() > 0){
				for(BusinessApplication temp:businessApplications){
					if(systemName.equals(temp.getName())){
						systemId = temp.getId();
					}
				}
			}
			FunctionTree functionTrees = AdapterFactory.getResourceService().getFuncTree(iscUserid, systemId, null);
			if(functionTrees != null){
				List<FunctionNode> nodeList = functionTrees.getFuncNode();
				getMenus(menus,nodeList);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return menus;
	}

	/**
	 * 递归获取所有权限范围内的菜单信息
	 */
	private void getMenus(List<String> menus,List<FunctionNode> nodeList){
		if(nodeList != null && nodeList.size() > 0){
			for(FunctionNode tempNode:nodeList){
				menus.add(tempNode.getCurrentNode().getName());
				getMenus(menus,tempNode.getNextNode());
			}
		}
	}


	@Log(title = "ISC同步业务用户", businessType = BusinessType.UPDATE)
	@RequestMapping("/synIscUser")
	public boolean synIscUser()
	{
		try {
			//ISC中当前系统ID
			String systemId = "";
			//获取ISC中所有的系统
			List<BusinessApplication> businessApplications = AdapterFactory.getDomainService().getBusinessApplication();
			if(businessApplications != null && businessApplications.size() > 0){
				for(BusinessApplication temp:businessApplications){
					if(systemName.equals(temp.getName())){
						systemId = temp.getCode();
					}
				}
			}
			//获取当前业务组织架构下的所有用户同步到系统
			List<User> iscUsers = AdapterFactory.getIdentityService().getUsersByOrg(systemId,ordId,null,null);
			if(iscUsers != null && iscUsers.size() > 0){
				for(User tempUser:iscUsers){
					SysUser sysUser = new SysUser();
					sysUser.setUserName(tempUser.getUserName());
					sysUser.setNickName(tempUser.getName());
					sysUser.setEmail(tempUser.getEmail());
					sysUser.setPhonenumber(tempUser.getMobile());
					sysUser.setSex(tempUser.getSexCode());
					sysUser.setPassword(pwd);
					sysUser.setRemark("ISC同步用户");
					remoteUserService.addIsc(sysUser);
				}
			}
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
}
